<template>
  <div class="app-container">


    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <div class="flex input-height">
        <div class="label">时间：</div>
        <div class="align-center">
          <el-radio-group v-model="cycleRadio" @change="bindchangeDate" class="margin-right">
            <el-radio-button label="day" v-if="route.query.type==1">本日</el-radio-button>
            <el-radio-button label="month">本月</el-radio-button>
            <el-radio-button label="season">本季</el-radio-button>
            <el-radio-button label="year">本年</el-radio-button>
          </el-radio-group>
          <el-date-picker style="margin-right:8px" v-model="dateSection" type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
            @change="bindChangeAllDate" />
        </div>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </div>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="[route.query.type==1?'audit:cyxxhz:add':route.query.type==2?'audit:txfzszxjhyb:add':'audit:ydzfxbg:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="[route.query.type==1?'audit:cyxxhz:export':route.query.type==2?'audit:txfzszxjhyb:export':'audit:ydzfxbg:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5" v-if="route.query.type==1">
        <el-button type="success" plain icon="Menu" @click="handleStatistics">统计</el-button>
      </el-col>
      <el-col :span="1.5" v-if="route.query.type!=1">
        <el-button @click="downloadAll" icon="Bottom" type="info">批量打包下载</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['charge:report:remove']">删除</el-button>
        </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <Custable :loading="loading" :content="goOutContent" :list="tableData" :queryParams="queryParams" :total="total" @getList="getList" :selection="true" @handleSelectionChange="handleSelectionChange" >
      <template #operation="scope" >
        <el-button link type="primary" icon="View" @click="handleUpdate(scope.row,1)"
          v-hasPermi="[route.query.type==1?'audit:cyxxhz:query':route.query.type==2?'audit:txfzszxjhyb:query':'audit:ydzfxbg:query']">查看详情</el-button>
        <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
          v-hasPermi="[route.query.type==1?'audit:cyxxhz:edit':route.query.type==2?'audit:txfzszxjhyb:edit':'audit:ydzfxbg:edit']">修改</el-button>
        <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
          v-hasPermi="[route.query.type==1?'audit:cyxxhz:remove':route.query.type==2?'audit:txfzszxjhyb:remove':'audit:ydzfxbg:remove']">删除</el-button>
      </template>
    </Custable>

    <Mask v-if="dialogVisible" :dialogVisible="dialogVisible" @handleClose="handleClose" :queryParams="queryParams" :rowDetails="rowDetails" :isView="isView"
      :title="title" :interface="carTypeList[radioIndex].interface" :formItemConfig="formItemConfig" />
    <Statistics :echartsData="statisticsData" ref="statisticsRef" @changeType="handleStatistics" />
  </div>
</template>
  
  
  <script setup>
import moment from 'moment'
import { listCyxxhz, getCyxxhz, delCyxxhz, postCyxxhzCount } from "@/api/charge/cyxxhz";
import { listYdzfxbg, getYdzfxbg, delYdzfxbg } from "@/api/charge/ydzfxbg";
import { listTxfzszxjhyb, getTxfzszxjhyb, delTxfzszxjhyb } from "@/api/charge/txfzszxjhyb";
import useUserStore from '@/store/modules/user'
import Custable from "@/components/Custom/Custable";
import Mask from "./components/Mask";
import Statistics from "./components/Statistics.vue";
import config from "./config"
import { ref } from 'vue';
import { getCKInfo } from '@/utils/auth'
const { proxy } = getCurrentInstance()
const userStore = useUserStore()
const route = useRoute();
const queryParams = ref({ "startDate": '', "endDate": '', pageNum: 1, pageSize: 10 })
const radioCarCon = ref('查验信息汇总')
const carTypeList = ref([
  { label: '查验信息汇总', value: "0", interface: 'Cyxxhz' },
  { label: '通行费征收专项稽核月报', value: "1", interface: 'Txfzszxjhyb' },
  { label: '月对账分析报告', value: "2", interface: 'Ydzfxbg' },
])
const cycleRadio = ref('month')
const dialogVisible = ref(false)
const goOutContent = ref(config.goOutContent1)
const formItemConfig = ref(config.formItemConfig1)
const loading = ref(false)
const deptOptions = ref([])
const tableData = ref([])
const total = ref(0)
const rowDetails = ref({ errorNo: 0 })
const dateSection = ref([])
const radioIndex = ref(0)
const methods = ref({ listCyxxhz, delYdzfxbg, listYdzfxbg, delTxfzszxjhyb, listTxfzszxjhyb, delCyxxhz })
const isView = ref(false)
const title = ref("新增")
const deptId = ref(Number(getCKInfo('deptId')))
const statisticsData = ref({ series: [{ data: [] }, { data: [] }], xaxis: [] })
const fileList = ref([])
const statisticsRef = ref()



const bindCarRadio = (name, val, index) => {
  goOutContent.value = config[`goOutContent${(Number(index))}`];
  formItemConfig.value = config[`formItemConfig${(Number(index))}`];
  radioIndex.value = val;
  tableData.value = [];
  getList('list' + carTypeList.value[val].interface)
}


/** 查询列表 */
function getList(abutment) {
  loading.value = true;
  methods.value[abutment ? abutment : 'list' + carTypeList.value[route.query.type - 1].interface](queryParams.value).then(response => {
    tableData.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
function handleSelectionChange(selection) {
  console.log(carTypeList.value[radioIndex.value],radioIndex.value)
  fileList.value = selection.map(item => item.fileAddress);  
  
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除该列编号为"' + _ids + '"的数据项？').then(function () {
    return methods.value['del' + carTypeList.value[radioIndex.value].interface](_ids);
  }).then(() => {
    getList('list' + carTypeList.value[radioIndex.value].interface);
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  // 
  let url = route.query.type == 1 ? 'audit/cyxxhz/export' : route.query.type == 2 ? 'audit/txfzszxjhyb/export' : 'audit/ydzfxbg/export';
  let name = route.query.type == 1 ? '查验信息汇总' : route.query.type == 2 ? '通行费征收专项稽核月报' : '月对账分析报告';
  proxy.download(url, {
    ...queryParams.value, deptId: deptId.value
  }, `${name}_${new Date().getTime()}.xlsx`)
}
const bindChangeAllDate = (val) => {
  if (!val) { dateSection.value = []; queryParams.value.startDate = ''; queryParams.value.endDate = ''; return }
  dateSection.value = [moment(val[0]).format("YYYY-MM-DD"), moment(val[1]).format("YYYY-MM-DD")]
  queryParams.value.startDate = dateSection.value[0];
  queryParams.value.endDate = dateSection.value[1];
}
/** 搜索按钮操作 */
function handleQuery() {
  getList('list' + carTypeList.value[radioIndex.value].interface)
};
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = { pageNum: 1, pageSize: 10 };

  if (route.query.type == 1) {
    cycleRadio.value = "day";
  } else {
    cycleRadio.value = "month";
  }
  proxy.resetForm("queryRef");
  init()
  handleQuery();
};
const handleAdd = () => {
  rowDetails.value = { errorNo: 0 }
  title.value = "新增"
  dialogVisible.value = true;
  isView.value = false;
}
const handleUpdate = (data, type) => {

  title.value = "修改"
  isView.value = type == 1 ? true : false;

  dialogVisible.value = true;
  rowDetails.value = data;
}

const handleClose = () => {
  dialogVisible.value = false;
  getList('list' + carTypeList.value[radioIndex.value].interface)
}
const bindchangeDate = (val) => {
  let date = new Date();
  let year = date.getFullYear();
  let params = {}
  if (val == 'day') {
    params.startDate = moment().format("YYYY-MM-DD")
    params.endDate = moment().format("YYYY-MM-DD");
  } else if (val == 'week') {
    params.startDate = moment().startOf('week').format('YYYY-MM-DD');
    params.endDate = moment().endOf('week').format('YYYY-MM-DD')
  } else if (val == 'month') {
    params.startDate = moment().startOf('month').format('YYYY-MM-DD');
    params.endDate = moment().endOf('month').format('YYYY-MM-DD')
  } else if (val == 'season') {
    let startQuarter = moment(moment().quarter(moment().quarter()).startOf('quarter').valueOf()).format('YYYY-MM-DD');
    let endQuarter = moment(moment().quarter(moment().quarter()).endOf('quarter').valueOf()).format('YYYY-MM-DD');
    params.startDate = startQuarter
    params.endDate = endQuarter
  } else {
    params.startDate = year + '-01-01'
    params.endDate = year + '-12-31'
  }
  dateSection.value = [moment(params.startDate).format("YYYY-MM-DD"), moment(params.endDate).format("YYYY-MM-DD")]
  queryParams.value = { ...queryParams.value, ...params }; getList('list' + carTypeList.value[radioIndex.value].interface)


}
const downloadAll = () => {
  if (fileList.value.length == 0) {
    proxy.$modal.msgError("您还未选中数据");
    return;
  }
  proxy.download('analysis/downloadAndZip', {
    ...queryParams.value,
    filePath: fileList.value.join(',')
  }, `${carTypeList.value[radioIndex.value].label}_${new Date().getTime()}.zip`)
}
const init = () => {


  if (route.query.type == 1) {
    cycleRadio.value = 'day'
    let day = moment().format('YYYY-MM-DD');
    queryParams.value.startDate = day;
    queryParams.value.endDate = day;
    dateSection.value = [day, day]
  } else {

    let startDate = moment().startOf('month').format('YYYY-MM-DD');
    let endDate = moment().endOf('month').format('YYYY-MM-DD')
    queryParams.value.startDate = startDate;
    queryParams.value.endDate = endDate;
    dateSection.value = [startDate, endDate]
  }

}
const getDeptId = () => {
  userStore.getInfo().then(res => {
    if (res.code == 200) {
      deptId.value = res.user.dept.deptId
      if (res.user.dept.deptId != 101) {
        config.goOutContent1.length >= 5 ? config.goOutContent1.splice(1, 1) : "";
        config.goOutContent2.length >= 5 ? config.goOutContent2.splice(1, 1) : "";
        config.goOutContent3.length >= 5 ? config.goOutContent3.splice(1, 1) : "";
      }
      // getList('listCyxxhz')
      if (route.query) {
        bindCarRadio(carTypeList.value[route.query.type - 1].label, route.query.type - 1, route.query.type)
      }
    }

  })
}

function handleStatistics(date) {
  // 本年  本季度  本月
  if (!date || !date.startDate) {
    date.startDate = moment().format('YYYY-MM') + '-01'
    date.endDate = moment().endOf('month').format('YYYY-MM-DD')
  }
  statisticsData.value.xaxis = []
  statisticsData.value.series[0].data = []
  postCyxxhzCount({
    "startTime": date.startDate,
    "endTime": date.endDate,
    tabType: 1,
    menuType: 11

  }).then(res => {
    if (res.code == 200 && res.data) {
      res.data.forEach(item => {
        statisticsData.value.xaxis.push(item.deptName)
        statisticsData.value.series[0].data.push(item.openCount)
      })
      statisticsRef.value.open();
    }
  })
}


getDeptId()
init()

  </script>
  
  <style scoped>
.flex {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.flex .label {
  color: #333;
  font-size: 14px;
}

/deep/.padding .el-radio-button--large .el-radio-button__inner {
  padding: 8px 19px;
}
/deep/ .custom-tag .el-radio-button--large .el-radio-button__inner {
  min-width: 60px;
  height: 32px;
  line-height: 32px;
  margin: 0 4px 0;
  padding: 0 10px;
  border: 1px solid #e4e4e4;
  font-size: 14px;
}
/deep/ .custom-tag .el-radio-button--large.is-active .el-radio-button__inner {
  background: #fff;
  border: 1px solid #246bcc;
  color: #246bcc;
  position: relative;
}

/deep/
  .custom-tag
  .el-radio-button--large.is-active
  .el-radio-button__inner:after {
  content: "";
  position: absolute;
  top: 0px;
  right: 0px;
  border-top: 20px solid #246bcc;
  border-left: 20px solid transparent;
}
/deep/
  .custom-tag
  .el-radio-button--large.is-active
  .el-radio-button__inner:before {
  content: "";
  position: absolute;
  width: 5px;
  height: 6px;
  background: transparent;
  top: 2px;
  right: 4px;
  border: 1px solid white;
  border-top: none;
  border-right: none;
  transform: rotate(-55deg);
  z-index: 9;
}

.margin-right {
  margin-right: 8px;
}
/deep/ .input-height .el-input__wrapper {
  height: 32px;
}
/deep/ .input-height .el-date-editor.el-input {
  height: 32px;
}
.margin-right-lg {
  margin-right: 32px;
}
.cursor {
  cursor: pointer;
}
.flex-end {
  margin-left: auto;
}
.active {
  position: relative;
}
.active::before {
  content: "";
  display: block;
  width: 50px;
  height: 2px;
  border-radius: 2px;
  background: var(--el-color-primary);
  position: absolute;
  bottom: 3px;
  left: 50%;
  transform: translateX(-50%);
}

.align-center {
  display: flex;
  align-items: center;
}
</style>